import React, { useLayoutEffect } from "react";
import { Root, Tooltip, Scrollbar } from "@amcharts/amcharts5";
import {
  XYChart,
  XYCursor,
  DateAxis,
  AxisRendererX,
  AxisRendererY,
  ValueAxis,
  LineSeries,
} from "@amcharts/amcharts5/xy";
import AnimatedTheme from "@amcharts/amcharts5/themes/Animated";

export interface LineProps {
  data: {
    value: number | string;
    date: number;
  }[];
}

export const Line: React.FC<LineProps> = ({ data = [] }) => {
  useLayoutEffect(() => {
    if (data.length === 0) return;

    // Create root element
    const root = Root.new("line");

    // Set themes
    root.setThemes([AnimatedTheme.new(root)]);

    // Create chart
    const chart = root.container.children.push(
      XYChart.new(root, {
        panX: true,
        panY: true,
        wheelX: "panX",
        wheelY: "zoomX",
        pinchZoomX: true,
        paddingLeft: 0,
      })
    );

    // Add cursor
    const cursor = chart.set(
      "cursor",
      XYCursor.new(root, {
        behavior: "none",
      })
    );
    cursor.lineY.set("visible", false);

    // Create axes
    const xAxis = chart.xAxes.push(
      DateAxis.new(root, {
        maxDeviation: 0.2,
        baseInterval: {
          timeUnit: "day",
          count: 1,
        },
        renderer: AxisRendererX.new(root, {
          minorGridEnabled: true,
        }),
        tooltip: Tooltip.new(root, {}),
      })
    );
    const yAxis = chart.yAxes.push(
      ValueAxis.new(root, {
        renderer: AxisRendererY.new(root, {
          pan: "zoom",
        }),
      })
    );

    // Add series
    const series = chart.series.push(
      LineSeries.new(root, {
        name: "Series",
        xAxis: xAxis,
        yAxis: yAxis,
        valueYField: "value",
        valueXField: "date",
        tooltip: Tooltip.new(root, {
          labelText: "{valueY}",
        }),
      })
    );

    // Add scrollbar
    chart.set(
      "scrollbarX",
      Scrollbar.new(root, {
        orientation: "horizontal",
      })
    );

    // Set data
    //data.forEach((date) => time.add(new Date(date), "day", 1));
    series.data.setAll(data);
    series.appear(1000);
    chart.appear(1000, 100);

    return () => root.dispose();
  }, [data]);
  return (
    <div
      style={{
        height: 300,
      }}
      id="line"
    />
  );
};
export default Line;
